package controller.UserController;

import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppVariable;
import common.ResultAjax;
import services.UserService;
import services.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */

// 初始化个人主页
@WebServlet("/initialize")
public class InitializeServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    //控制层调用服务层
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");
        // 1、校验
        // 校验登陆身份
        HttpSession session = req.getSession(false);
        if (session == null) {
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"未登录，请先登录！"));
            resp.getWriter().write(respJson);
            return ;
        }
        User user = (User) session.getAttribute(AppVariable.SESSION_USERINFO_KEY);
        System.out.println("user:"+user);
        if(user == null){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"用户不存在！"));
            resp.getWriter().write(respJson);
            return ;
        }
        System.out.println(user.getPhoneNumber().trim());
        user = userService.getUserByPhoneNumber(user.getPhoneNumber().trim());
        if(user!=null){
            String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(user));
            resp.getWriter().write(respJson);
        }else{
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"用户不存在！"));
            resp.getWriter().write(respJson);
            return ;
        }
    }
}
